#include "List.h"

ListNode* BuyListNode(LTDataType x)
{
	ListNode* node = (ListNode*)malloc(sizeof(ListNode));
	if (node == NULL)
	{
		perror("malloc fail!");
		exit(1);
	}
	node->x = x;
	node->next = node;
	node->prev = node;
	return node;
}
ListNode* LTInit()
{
	ListNode* phead = BuyListNode(-1);
	return phead;
}

void LTPushBack(ListNode* phead, LTDataType x)
{
	assert(phead);
	ListNode* newnode = BuyListNode(x);
	newnode->prev = phead->prev;
	newnode->next = phead;
	phead->prev->next = newnode;
	phead->prev = newnode;
}
void LTPushFront(ListNode* phead, LTDataType x)
{
	assert(phead);
	ListNode* newnode = BuyListNode(x);
	newnode->next = phead->next;
	newnode->prev = phead;
	phead->next->prev = newnode;
	phead->next = newnode;
}

void LTPrint(ListNode* phead)
{
	assert(phead && phead->next != phead);
	ListNode* pcur = phead->next;
	while (pcur != phead)
	{
		printf("%d ", pcur->x);
		pcur = pcur->next;
	}
	printf("\n");
}
void LTInsert(ListNode* pos, LTDataType x)
{
	assert(pos);
	ListNode* newnode = BuyListNode(x);
	newnode->next = pos->next;
	newnode->prev = pos;
	pos->next->prev = newnode;
	pos->next = newnode;
}

ListNode* LTFind(ListNode* phead, LTDataType x)
{
	assert(phead && phead->next != phead);
	ListNode* pcur = phead->next;
	while (pcur != phead)
	{
		if (pcur->x == x)
		{
			return pcur;
		}
		pcur = pcur->next;
	}
	return NULL;
}

void LTPopBack(ListNode* phead)
{
	assert(phead && phead->next != phead);
	ListNode* del = phead->prev;
	del->prev->next = phead;
	phead->prev = del->prev;
	free(del);
	del = NULL;
}

void LTPopFront(ListNode* phead)
{
	assert(phead && phead->next != phead);
	ListNode* del = phead->next;
	del->next->prev = phead;
	phead->next = del->next;
	free(del);
	del = NULL;
}

void LTErase(ListNode* del)
{
	assert(del);
	del->next->prev = del->prev;
	del->prev->next = del->next;
	free(del);
	del = NULL;
}
void LTDestroy(ListNode* phead)
{
	assert(phead);
	ListNode* del = phead->next;
	while (del != phead)
	{
		ListNode* newdel = del->next;
		free(del);
		del = newdel;
	}
	free(phead);
	phead = NULL;
}